package com.sskj.mine.ui.activity;


import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bulong.rudeness.RudenessScreenHelper;
import com.lzy.okgo.OkGo;
import com.sskj.common.util.ClickUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.SPConfig;
import com.sskj.lib.util.AppToastInnerCheckUtil;
import com.sskj.mine.R;
import com.sskj.mine.R2;
import com.sskj.mine.bean.PayWayBean;
import com.sskj.mine.bean.PersonCenterItemBean;
import com.sskj.mine.component.DaggerUserDataComponent;
import com.sskj.mine.presenter.SecurityCenterActivityPresenter;
import com.sskj.mine.util.HideUtil;
import com.sskj.mine.util.TipMineUtil;
import com.sskj.common.adapter.ItemClickSupport;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;

@Route(path = RConfig.MINE_SECURITY_CENTER)//安全中心
public class SecurityCenterActivity extends BaseActivity<SecurityCenterActivityPresenter> {
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.recyclerViewPayType)
    RecyclerView recyclerViewPayType;
    @BindView(R2.id.tvAddPayType)
    TextView tvAddPayType;
    @Inject
    UserViewModel userViewModel;
    private UserData userData;
    private SlimAdapter<PersonCenterItemBean> slimAdapter;
    private MaterialDialog tip;
    private SlimAdapter slimAdapterPayType;

    @Override
    protected int getLayoutResId() {
        return R.layout.mine_activity_security_center;
    }

    @Override
    public SecurityCenterActivityPresenter getPresenter() {
        return new SecurityCenterActivityPresenter();
    }

    @Override
    protected void initView() {
        setTitle(App.INSTANCE.getString(R.string.mineSecurityCenterActivity0));
        DaggerUserDataComponent.create().inject(this);
        initRecy();
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
                OkGo.getInstance().getCommonHeaders().put(SPConfig.ACCOUNT, users.get(0).getAccount());
                OkGo.getInstance().getCommonParams().put(SPConfig.ACCOUNT, users.get(0).getAccount());
                OkGo.getInstance().getCommonHeaders().put(SPConfig.MOBILE, users.get(0).getMobile());
                OkGo.getInstance().getCommonParams().put(SPConfig.MOBILE, users.get(0).getMobile());
            } else {
                userData = null;
            }
            updateUI();
        });
        //添加支付方式
        ClickUtil.click(tvAddPayType, () -> {
            if (userData == null) {
                return;
            }
            if (AppToastInnerCheckUtil.checkTradePwd(this, userData)) {
                ARouter.getInstance().build(RConfig.MINE_PAY_TYPE_UPDATE).withBoolean(Constans.IS_ADD, true).navigation();
            }
        });
    }

    @Override
    protected void initData() {
        userViewModel.update();
        mPresenter.getPayType();
    }

    @Override
    protected void onRestart() {
        userViewModel.update();
        super.onRestart();
    }

    @Override
    protected void onResume() {
        if (mPresenter != null) {
            mPresenter.getPayType();
        }
        super.onResume();
    }

    private void initRecy() {
        HashMap<String, String> payMapName = new HashMap<>();
        payMapName.put("1", getString(R.string.mine_wechat));
        payMapName.put("2", getString(R.string.mine_alipay));
        payMapName.put("3", getString(R.string.mine_bank));
        HashMap<String, Integer> payMapIcon = new HashMap<>();
        payMapIcon.put("wx", R.mipmap.mine_icon_pay_type_weixin);
        payMapIcon.put("alipay", R.mipmap.mine_icon_pay_type_alipay);
        payMapIcon.put("backcard", R.mipmap.mine_icon_pay_type_bank);
        payMapIcon.put("paypal", R.mipmap.mine_icon_pay_type_paypal);
        ArrayList<PersonCenterItemBean> itemBeans = new ArrayList<>();
        itemBeans.add(new PersonCenterItemBean(App.INSTANCE.getString(R.string.mineSecurityCenterActivity1), App.INSTANCE.getString(R.string.mineSecurityCenterActivity8)));
        itemBeans.add(new PersonCenterItemBean(App.INSTANCE.getString(R.string.mineSecurityCenterActivity3), App.INSTANCE.getString(R.string.mineSecurityCenterActivity8)));
        itemBeans.add(new PersonCenterItemBean(App.INSTANCE.getString(R.string.mineSecurityCenterActivity5), App.INSTANCE.getString(R.string.mineSecurityCenterActivity6)));
        itemBeans.add(new PersonCenterItemBean(App.INSTANCE.getString(R.string.mineSecurityCenterActivity7), App.INSTANCE.getString(R.string.mineSecurityCenterActivity8)));
        itemBeans.add(new PersonCenterItemBean(App.INSTANCE.getString(R.string.mineSecurityCenterActivity9), App.INSTANCE.getString(R.string.mineSecurityCenterActivity10)));
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(this)
                .setFirstDraw(false)
                .setLastDraw(false)
                .setLeftPadding((int) RudenessScreenHelper.pt2px(App.INSTANCE, 32))
                .setDividerColor(ContextCompat.getColor(App.INSTANCE, R.color.mine_525869))
                .setPaintWidth((int) RudenessScreenHelper.pt2px(App.INSTANCE, 2)));
        slimAdapter = SlimAdapter.create().register(R.layout.mine_recy_item_security_center, new SlimInjector<PersonCenterItemBean>() {
            @Override
            public void onInject(PersonCenterItemBean data, IViewInjector injector, List payloads) {
                injector
                        .text(R.id.tvTitle, data.getTitle())
                        .text(R.id.tvContent, data.getContent());
            }
        }).attachTo(recyclerView).updateData(itemBeans);
        recyclerViewPayType.addItemDecoration(new DividerLineItemDecoration(this)
                .setFirstDraw(true)
                .setLastDraw(false)
                .setDividerColor(ContextCompat.getColor(App.INSTANCE, R.color.mine_525869))
                .setPaintWidth((int) RudenessScreenHelper.pt2px(App.INSTANCE, 2)));
        recyclerViewPayType.setLayoutManager(new LinearLayoutManager(this));
        slimAdapterPayType = SlimAdapter.create().register(R.layout.mine_recy_item_security_center_pay_type, new SlimInjector<PayWayBean.PayListBean>() {
            @Override
            public void onInject(PayWayBean.PayListBean data, IViewInjector injector, List payloads) {
                injector
                        .image(R.id.ivPayType, payMapIcon.get(data.getType()))
                        .text(R.id.tvPayType, data.getTip())
                        .text(R.id.tvName, data.getName())
                        .text(R.id.tvPayName, data.getTip())
                        .text(R.id.tvAccount, data.getNumber())
                        .checked(R.id.checkBox, !data.getStatus().equals("0"))
                        .clicked(R.id.tvChange, (v) -> {
                            ARouter.getInstance().build(RConfig.MINE_PAY_TYPE_UPDATE)
                                    .withBoolean(Constans.IS_ADD, false)
                                    .withString(Constans.PAY_ID, data.getType())
                                    .withInt(Constans.INIT_POS, Integer.valueOf(data.getId()) - 1)
                                    .navigation();
                        })
                        .clicked(R.id.checkBox, (v) -> {
                            mPresenter.togglePay(data.getType(), data.getStatus().equals("0") ? "1" : "0");
                        });
            }
        }).attachTo(recyclerViewPayType).updateData(new ArrayList());
        ItemClickSupport.addTo(recyclerView)
                .setOnItemClickListener((recyclerView1, position, v) -> {
                    if (userData == null) {
                        userViewModel.update();
                        return;
                    }
                    switch (position) {
                        case 0://手机
//                            if (userData.getWay().equals("mobile")) {
//                                ToastUtil.showShort(R.string.mineRegisterActivity1);
//                                return;
//                            }
                            if (TextUtils.isEmpty(userData.getMobile())) {
                                ARouter.getInstance().build(RConfig.MINE_BIND_MOBILE).navigation();
                            } else {
                                ToastUtil.showShort("手机号一旦被绑定，均不可以再被更改");
                            }
                            break;
                        case 1://邮箱
                            if (userData.getWay().equals("email")) {
                                ToastUtil.showShort(R.string.mineRegisterActivity1);
                                return;
                            }
                            ARouter.getInstance().build(RConfig.MINE_BIND_EMAIL).navigation();
                            break;
                        case 2://登录密码
                            ARouter.getInstance().build(RConfig.MINE_PWD_CHANGE).navigation();
                            break;
                        case 3://支付密码
                            if (AppToastInnerCheckUtil.checkAuth(SecurityCenterActivity.this, userData)) {
                                ARouter.getInstance().build(RConfig.MINE_SET_PAY_PWD).navigation();
                            }
                            break;
                        case 4://实名认证
                            if (AppToastInnerCheckUtil.checkTel(SecurityCenterActivity.this, userData)) {
                                checkIdent();
                            }
                            break;
                    }
                });
    }


    /**
     * 判断用户实名认证
     */
    public void checkIdent() {
        switch (userData.getStatus()) {
            case 3:
                ToastUtil.showShort(App.INSTANCE.getString(R.string.mineSecurityCenterActivity13));
                break;
            case 2:
                showApplyTip(App.INSTANCE.getString(R.string.mineSecurityCenterActivity14), false);
                break;
            default:
                ARouter.getInstance().build(RConfig.MINE_CERTIFICATION).navigation();
                break;
        }
    }

    /**
     * 判断用户实名认证弹窗
     */
    private void showApplyTip(String msg, boolean status) {
        if (tip == null) {
            tip = TipMineUtil.getTip(this, App.INSTANCE.getString(R.string.mineSecurityCenterActivity15),
                    msg,
                    App.INSTANCE.getString(R.string.mineSecurityCenterActivity17),
                    () -> {
                        tip.dismiss();
                        if (status) {
                            ARouter.getInstance().build(RConfig.MINE_CERTIFICATION).navigation();
                        }
                    });
        }
        tip.show();
    }

    private void updateUI() {
        if (userData == null) {
            return;
        }
        if (TextUtils.isEmpty(userData.getMobile())) {
            slimAdapter.getData().get(0).setContent(App.INSTANCE.getString(R.string.mineSecurityCenterActivity8));
        } else {
            slimAdapter.getData().get(0).setContent(HideUtil.getPhoneHide(userData.getMobile()));
        }
        if (TextUtils.isEmpty(userData.getMail())) {
            slimAdapter.getData().get(1).setContent(App.INSTANCE.getString(R.string.mineSecurityCenterActivity8));
        } else {
            slimAdapter.getData().get(1).setContent(userData.getMail());
        }
        if (TextUtils.isEmpty(userData.getTpwd())) {
            slimAdapter.getData().get(3).setContent(App.INSTANCE.getString(R.string.mineSecurityCenterActivity8));
        } else {
            slimAdapter.getData().get(3).setContent(App.INSTANCE.getString(R.string.mineSecurityCenterActivity6));
        }
        switch (userData.getStatus()) {       // 实名认证
            case 1:
                slimAdapter.getData().get(4).setContent(App.INSTANCE.getString(R.string.mineSecurityCenterActivity10));
                break;
            case 2:
                slimAdapter.getData().get(4).setContent(App.INSTANCE.getString(R.string.mineSecurityCenterActivity26));
                break;
            case 3:
                slimAdapter.getData().get(4).setContent(App.INSTANCE.getString(R.string.mineSecurityCenterActivity27));
                break;
            case 4:
                slimAdapter.getData().get(4).setContent(App.INSTANCE.getString(R.string.mineSecurityCenterActivity28));
                break;
        }

        slimAdapter.notifyItemRangeChanged(0, 5);

    }

    public void setPayType(List<PayWayBean.PayListBean> payWayBeans) {
        if (payWayBeans.size() >= 4) {
            tvAddPayType.setVisibility(View.GONE);
        } else {
            tvAddPayType.setVisibility(View.VISIBLE);
        }
        slimAdapterPayType.updateData(payWayBeans);
    }

    public void toggleShopSuccess() {
        userViewModel.update();
    }

    public void togglePayTypeSuccess() {
        userViewModel.update();
        mPresenter.getPayType();
    }
}
